
package com.iceland.client.client.cmd;

import com.iceland.common.message.CmdMessage;
import com.iceland.common.thread.MessageEventExcutor;
import com.iceland.common.strategy.CmdStrategyFactory;
import com.iceland.common.util.AttributeKeyUtils;
import com.iceland.common.util.ChannelContext;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class CmdHandler extends ChannelInboundHandlerAdapter {


    public CmdHandler(){
    }


    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {


    }


    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        CmdMessage m=(CmdMessage)msg;

        int type = m.getType();
        CmdStrategyFactory.getStrategy(type).doStrategy(ctx,m);

        //此处不应该使用多线程执行，因为一个handler绑定了一个线程，如果多个线程操作这个handler，那么就导致这个tcp接收到的消息被并发处理，导致消息呈现无序的状态
//        MessageEventExcutor.getInstance().submit(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    CmdStrategyFactory.getStrategy(type).doStrategy(ctx,m);
//
//                }catch (Throwable e){
//                    log.error("CmdStrategy执行失败",e);
//                }
//            }
//        });

        ctx.fireChannelRead(msg);
    }

    //断开
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        log.info("通道关闭，l:{},r：{}",channel.localAddress(),channel.remoteAddress());

        ChannelContext channelContext = AttributeKeyUtils.getChannelContext(channel);
        if(channelContext!=null && channelContext.getBindChannel()!=null){
            channelContext.getBindChannel().close();
        }
        ctx.fireChannelInactive();
    }

}
